import paddle
import cv2
import numpy as np
from ppdet.core.workspace import create
from ppdet.engine import Trainer
from ppdet.utils.checkpoint import load_weight

def predict_image(image_path):
    # 创建训练器
    trainer = Trainer()
    
    # 加载预训练模型
    weights_url = 'https://paddledet.bj.bcebos.com/models/yolov3_mobilenet_v1_270e_coco.pdparams'
    trainer.model = load_weight(trainer.model, weights_url)
    trainer.model.eval()
    
    # 读取图像
    img = cv2.imread(image_path)
    if img is None:
        raise ValueError('无法读取图像，请检查图像路径')
    
    # 执行预测
    results = trainer.predict([img], visualize=True)[0]
    
    # 保存结果
    cv2.imwrite('detection_result.jpg', results['visual'])
    print('检测结果已保存为 detection_result.jpg')

if __name__ == '__main__':
    # 替换为你的测试图片路径
    image_path = 'test.jpg'
    predict_image(image_path)